package com.googlecode.gwt4gae.server;

import java.io.Serializable;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import com.googlecode.gwt4gae.client.IBaseService;

public abstract class BaseServiceImpl<E extends Serializable> extends
		RemoteServiceServlet implements IBaseService<E> {
	private static final long serialVersionUID = 3657842986000625926L;

	protected PersistenceManager pm = PMF.get().getPersistenceManager();

	public void persist(E entity) {
		pm.makePersistent(entity);
	}

	public void persistBatch(List<E> entities) {
		try {
			pm.currentTransaction().begin();
			for (E e : entities) {
				pm.makePersistent(e);
			}
			pm.currentTransaction().commit();
		} finally {
			if (pm.currentTransaction().isActive()) {
				pm.currentTransaction().rollback();
			}
		}
	}

	public void remove(E entity) {
		pm.deletePersistent(entity);

	}

	public void removeBatch(List<E> entities) {
		try {
			pm.currentTransaction().begin();
			for (E e : entities) {
				pm.deletePersistent(e);
			}
			pm.currentTransaction().commit();
		} finally {
			if (pm.currentTransaction().isActive()) {
				pm.currentTransaction().rollback();
			}
		}
	}

	public void update(E entity) {
		pm.makePersistent(entity);
	}

	public void updateBatch(List<E> entities) {
		try {
			pm.currentTransaction().begin();
			for (E e : entities) {
				pm.makePersistent(e);
			}
			pm.currentTransaction().commit();
		} finally {
			if (pm.currentTransaction().isActive()) {
				pm.currentTransaction().rollback();
			}
		}
	}
}
